/*
 * Created by Wildish on 2016-11-17
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 */

package com.wildish.hfdemo.proxy.alipay;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.alipay.sdk.app.PayTask;
import com.wildish.hfdemo.utils.Global;
import com.wildish.hybridframework.core.HybridGlobal;
import com.wildish.hybridframework.jsbinding.proxy.BaseHybridProxy;
import com.wildish.hybridframework.jsbinding.proxy.HybridProxy;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class AlipayProxy extends BaseHybridProxy {
    public static final String ALIPAY_ACTION_PAY = "action_pay";

    public AlipayProxy(String key) {
        super(key);
    }

    @Override
    public void release() {

    }

    @Override
    public void execute(Context context, String action, JSONObject params) {
        switch(action) {
            case ALIPAY_ACTION_PAY:
                doPay(params);
                break;
        }
    }

    private void doPay(JSONObject params) {
        try{
            // 获取支付信息
            String orderInfo = AlipayUtil.generateOrder(
                    params.getString("traderNo"),
                    params.getString("subject"),
                    params.getString("body"),
                    params.getString("totalFee"),
                    Global.SERVER_NOTIFY_URL);

            // 签名
            String sign = AlipayUtil.sign(orderInfo);
            try {
                sign = URLEncoder.encode(sign, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + "sign_type=\"RSA\"";
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(HybridGlobal.getCurrentWebViewContext());
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(payInfo, true);
                    PayResult payResult = new PayResult(result);

                    String payResultStr = "{\"success\": false}";
                    try{
                        JSONObject obj = new JSONObject();
                        if(payResult.getResultStatus().equals("8000") || payResult.getResultStatus().equals("9000")) {
                            obj.put("success", true);
                            obj.put("stauts", payResult.getResultStatus());
                        } else {
                            obj.put("success", false);
                        }
                        payResultStr = obj.toString();
                    } catch (Exception e) {
                        HybridGlobal.logger.log(e);
                    }

                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("result", payResultStr);
                    message.setData(bundle);
                    alipayHandler.sendMessage(message);
                }
            };
            // 必须异步调用
            Global.pool.submit(payRunnable);
        } catch(Exception e) {

        }
    }

    private Handler alipayHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String result = msg.getData().getString("result");
            AlipayProxy.super.sendToWebview(key, ALIPAY_ACTION_PAY, result);
        }
    };
}
